package com.hank.snakegame;

import java.awt.*;
import java.util.LinkedList;

public class Snake {
    private void init(){
        int startX = GamePanel.COL_NUM/2 -1;
        int startY = GamePanel.ROW_NUM/2-1;

        snakeCells.add(new Cell(startX,startY,Color.RED));
        snakeCells.add(new Cell(startX+1,startY,Color.BLUE));
        snakeCells.add(new Cell(startX+2,startY,Color.BLUE));
    }

    public Snake() {init();}

    //LinkedList得使用
    private LinkedList<Cell> snakeCells = new LinkedList<>();

    public void paint(Graphics g){
        for(Cell cell : snakeCells){
            g.setColor(cell.getColor());
            g.fill3DRect(cell.getX()*GamePanel.CELL_UNIT,cell.getY()*GamePanel.CELL_UNIT,GamePanel.CELL_UNIT,GamePanel.CELL_UNIT,true);
        }
    }

    public boolean mobeHead(int changeX,int changeY){

        Cell oldHead = snakeCells.getFirst();

        Cell newHead =new Cell(oldHead.getX()+changeX,oldHead.getY()+changeY,Color.RED);

        //1.撞墙
        if(isCashWall(newHead)){
            System.out.println("撞墙上了");
            return false;
        }

        //2.撞自己
        if (snakeCells.contains(newHead)){
            System.out.println("撞自己身上了");
            return false;
        }

        //撞墙上了
        isDrillDeadEnds(newHead);

        oldHead.setColor(Color.BLUE);
        snakeCells.addFirst(newHead);
        return true;
    }

    private boolean isCashWall(Cell newHead){
        return newHead.getX()<0 || newHead.getX() >= GamePanel.COL_NUM || newHead.getY() < 0 || newHead.getY() >= GamePanel.ROW_NUM;
    }

    public boolean isDrillDeadEnds(Cell newHead){

        boolean hasBeforeXCell =false;
        boolean hasAfterXCell = false;
        boolean hasBeforeYCell = false;
        boolean hasAfterYCell = false;
        for(int i=0;i<snakeCells.size();i++){
            Cell currCell = snakeCells.get(i);

            //1.定y，夹x
            if(currCell.getY()==newHead.getY() && currCell.getX()<newHead.getX()){hasBeforeXCell=true;}
            if(currCell.getY()==newHead.getY() && currCell.getX()>newHead.getX()){hasAfterXCell=true;}

            //2.定x,夹y
            if(currCell.getX()==newHead.getX() && currCell.getY()<newHead.getY()){hasBeforeYCell=true;}
            if(currCell.getX()==newHead.getX() && currCell.getY()>newHead.getY()){hasAfterYCell=true;}
        }

        if(hasBeforeXCell && hasAfterXCell && hasBeforeYCell && hasAfterYCell){
            return true;
        }
        return false;
    }


    public boolean eatFood(Food food){
        return snakeCells.getFirst().equals(food);
    }

    public void removeTail(){
        snakeCells.removeLast();
    }

    public LinkedList<Cell>getSnakeCells(){
        return snakeCells;
    }
}
